package cn.lili.controller.passport;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dto.AuthVerifyDto;
import cn.lili.modules.member.entity.dto.MemberEditDTO;
import cn.lili.modules.member.entity.dto.PaymentPwdDto;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.entity.vo.PaymentPwdVo;
import cn.lili.modules.member.entity.vo.RevokeApplyVo;
import cn.lili.modules.member.entity.vo.RevokePartnerVo;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.sms.SmsUtil;
import cn.lili.modules.verification.entity.enums.VerificationEnums;
import cn.lili.modules.verification.service.VerificationService;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 买家端,会员接口
 *
 * @author Chopper
 * @since 2020/11/16 10:07 下午
 */
@Slf4j
@RestController
@Api(tags = "买家端,会员接口")
@RequestMapping("/buyer/members")
public class MemberBuyerController {

	@Autowired
	private MemberService memberService;
	@Autowired
	private SmsUtil smsUtil;
	@Autowired
	private VerificationService verificationService;

	@Autowired
	private EextensionService eextensionService;

	@ApiOperation(value = "登录接口")
	@ApiImplicitParams({@ApiImplicitParam(name = "username", value = "用户名", required = true, paramType = "query"),
			@ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query")})
	@RequestMapping("/userLogin")
	public ResultMessage<Object> userLogin(@NotNull(message = "用户名不能为空") @RequestParam String username,
			@NotNull(message = "密码不能为空") @RequestParam String password, @RequestHeader String uuid) {
		verificationService.check(uuid, VerificationEnums.LOGIN);
		return ResultUtil.data(this.memberService.usernameLogin(username, password));
	}

	@ApiOperation(value = "注销接口")
	@RequestMapping("/logout")
	public ResultMessage<Object> logout() {
		this.memberService.logout(UserEnums.MEMBER);
		return ResultUtil.success();
	}

	@ApiOperation(value = "短信登录接口")
	@ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "手机号", required = true, paramType = "query"),
			@ApiImplicitParam(name = "code", value = "验证码", required = true, paramType = "query")})
	@RequestMapping("/smsLogin")
	public ResultMessage<Object> smsLogin(@NotNull(message = "手机号为空") @RequestParam String mobile,
			@NotNull(message = "验证码为空") @RequestParam String code, @RequestHeader String uuid) {
		if (smsUtil.verifyCode(mobile, VerificationEnums.LOGIN, uuid, code)) {
			return ResultUtil.data(memberService.mobilePhoneLogin(mobile));
		} else {
			throw new ServiceException(ResultCode.VERIFICATION_SMS_CHECKED_ERROR);
		}
	}

	@ApiOperation(value = "注册用户")
	@ApiImplicitParams({@ApiImplicitParam(name = "username", value = "用户名", required = true, paramType = "query"),
			@ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query"),
			@ApiImplicitParam(name = "mobilePhone", value = "手机号", required = true, paramType = "query"),
			@ApiImplicitParam(name = "code", value = "验证码", required = true, paramType = "query")})
	@RequestMapping("/register")
	public ResultMessage<Object> register(@NotNull(message = "用户名不能为空") @RequestParam String username,
			@NotNull(message = "密码不能为空") @RequestParam String password,
			@NotNull(message = "手机号为空") @RequestParam String mobilePhone, @RequestHeader String uuid,
			@NotNull(message = "验证码不能为空") @RequestParam String code) {

		if (smsUtil.verifyCode(mobilePhone, VerificationEnums.REGISTER, uuid, code)) {
			return ResultUtil.data(memberService.register(username, password, mobilePhone));
		} else {
			throw new ServiceException(ResultCode.VERIFICATION_SMS_CHECKED_ERROR);
		}

	}

	@ApiOperation(value = "获取当前登录用户接口")
	@GetMapping
	public ResultMessage<MemberVO> getUserInfo(@RequestParam("extensionCode") String extensionCode) {

		return ResultUtil.data(memberService.getUserInfos("BUYER", null, extensionCode));
	}

	@ApiOperation(value = "通过短信重置密码")
	@ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "手机号", required = true, paramType = "query"),
			@ApiImplicitParam(name = "password", value = "是否保存登录", required = true, paramType = "query"),
			@ApiImplicitParam(name = "newPassword", value = "新密码", required = true, paramType = "query")})
	@RequestMapping("/resetByMobile")
	public ResultMessage<Member> resetByMobile(@NotNull(message = "手机号为空") @RequestParam String mobile,
			@NotNull(message = "验证码为空") @RequestParam String code,
			@NotNull(message = "新的密码") @RequestParam String newPassword, @RequestHeader String uuid) {
		// 校验短信验证码是否正确
		if (smsUtil.verifyCode(mobile, VerificationEnums.FIND_USER, uuid, code)) {
			// 校验是否通过手机号可获取会员,存在则将会员信息存入缓存，有效时间3分钟
			memberService.findByMobile(uuid, mobile);
			// 检验完毕后修改会员密码
			modifyPass(null, newPassword);
			return ResultUtil.success();
		} else {
			throw new ServiceException(ResultCode.VERIFICATION_SMS_CHECKED_ERROR);
		}
	}

	@ApiOperation(value = "修改密码")
	@ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "手机号", required = true, paramType = "query"),
			@ApiImplicitParam(name = "password", value = "是否保存登录", required = true, paramType = "query")})
	@RequestMapping("/resetPassword")
	public ResultMessage<Object> resetByMobile(@NotNull(message = "密码为空") @RequestParam String password,
			@RequestHeader String uuid) {

		return ResultUtil.data(memberService.resetByMobile(uuid, password));
	}

	@ApiOperation(value = "修改用户自己资料")
	@PutMapping("/editOwn")
	public ResultMessage<Member> editOwn(MemberEditDTO memberEditDTO) {

		return ResultUtil.data(memberService.editOwn(memberEditDTO));
	}

	@ApiOperation(value = "修改密码")
	@ApiImplicitParams({@ApiImplicitParam(name = "password", value = "旧密码", required = false, paramType = "query"),
			@ApiImplicitParam(name = "newPassword", value = "新密码", required = true, paramType = "query")})
	@RequestMapping("/modifyPass")
	public ResultMessage<Member> modifyPass(@RequestParam String password,
			@NotNull(message = "新密码不能为空") @RequestParam String newPassword) {
		return ResultUtil.data(memberService.modifyPass(password, newPassword));
	}

	@ApiOperation(value = "刷新token")
	@RequestMapping("/refresh/{refreshToken}")
	public ResultMessage<Object> refreshToken(@NotNull(message = "刷新token不能为空") @PathVariable String refreshToken) {
		return ResultUtil.data(this.memberService.refreshToken(refreshToken));
	}

	@ApiOperation(value = "实名认证")
	@ApiImplicitParams({@ApiImplicitParam(name = "realName", value = "姓名", required = true, paramType = "query"),
			@ApiImplicitParam(name = "idCardNumber", value = "身份证号", required = true, paramType = "query")})
	@RequestMapping("/authentication")
	public ResultMessage<Member> authentication(@NotNull(message = "姓名不能为空") @RequestParam String realName,
			@NotNull(message = "身份证号不能为空") @RequestParam String idCardNumber) {
		return ResultUtil.data(memberService.authentication(realName, idCardNumber));
	}

	@ApiOperation(value = "实名认证")
	@RequestMapping("/authVerify")
	public ResultMessage<Member> authVerify(AuthVerifyDto authVerifyDto) {
		return ResultUtil.data(memberService.authVerify(authVerifyDto));
	}

	@ApiOperation(value = "修改、忘记支付密码")
	@RequestMapping("/setPaymentPwd")
	public ResultMessage<Member> setPaymentPwd(@RequestBody PaymentPwdDto paymentPwdDto) {
		AuthUser authUser = UserContext.getCurrentUser();
		if (authUser == null) {
			throw new ServiceException(ResultCode.USER_NOT_LOGIN);
		}
		paymentPwdDto.setMemberId(authUser.getId());
		log.info("修改、忘记支付密码,入参:{}", JSON.toJSONString(paymentPwdDto));
		if (smsUtil.verifyCode(paymentPwdDto.getMobile(), VerificationEnums.WALLET_PASSWORD,
				paymentPwdDto.getMemberId(), paymentPwdDto.getMsgCode())) {
			return ResultUtil.data(memberService.setPaymentPwd(paymentPwdDto));
		} else {
			throw new ServiceException(ResultCode.VERIFICATION_SMS_CHECKED_ERROR);
		}
	}

	@ApiOperation(value = "设置支付密码")
	@RequestMapping("/initPaymentPwd")
	public ResultMessage<Member> initPaymentPwd(PaymentPwdDto paymentPwdDto) {
		AuthUser authUser = UserContext.getCurrentUser();
		if (authUser == null) {
			throw new ServiceException(ResultCode.USER_NOT_LOGIN);
		}
		paymentPwdDto.setMemberId(authUser.getId());
		return ResultUtil.data(memberService.initPaymentPwd(paymentPwdDto));
	}

	@ApiOperation(value = "获取当前密码管理")
	@RequestMapping("/getPaymentPwd")
	public ResultMessage<PaymentPwdVo> getPaymentPwd() {
		AuthUser authUser = UserContext.getCurrentUser();
		if (authUser == null) {
			return ResultUtil.error(ResultCode.USER_NOT_LOGIN);
		}
		return ResultUtil.data(memberService.getPaymentPwd(authUser.getId()));
	}

	@ApiOperation(value = "验证是否存在注销合伙人申请")
	@RequestMapping("/revokePartnerVerify")
	public ResultMessage<Boolean> revokePartnerVerify() {
		AuthUser authUser = UserContext.getCurrentUser();
		if (authUser == null) {
			return ResultUtil.error(ResultCode.USER_NOT_LOGIN);
		}
		return ResultUtil.data(memberService.revokePartnerVerify(authUser.getId()));
	}

	/**
	 * 撤销合伙人 根据memberId 获取li_partner 表的合伙人数据 更新 partner_state 、delete_flag 字段
	 * 根据memberId 获取 li_member 表会员数据 根据推广码 promotion_code字段 获取li_extension 数据
	 * 更新delete_flag 字段
	 * 
	 * @return
	 */
	@ApiOperation(value = "注销合伙人申请页")
	@RequestMapping("/revokePartnerPage")
	public ResultMessage<RevokePartnerVo> revokePartnerPage() {
		AuthUser authUser = UserContext.getCurrentUser();
		if (authUser == null) {
			return ResultUtil.error(ResultCode.USER_NOT_LOGIN);
		}
		return ResultUtil.data(memberService.revokePartnerPage(authUser.getId()));
	}

	@ApiOperation(value = "注销合伙人--申请按钮")
	@RequestMapping("/applyRevokePartner")
	public ResultMessage<Boolean> applyRevokePartner(@RequestParam("revokeMsg") String revokeMsg) {
		if (StringUtils.isEmpty(revokeMsg)) {
			throw new ServiceException(ResultCode.PARAMS_ERROR);
		}
		AuthUser authUser = UserContext.getCurrentUser();
		if (authUser == null) {
			return ResultUtil.error(ResultCode.USER_NOT_LOGIN);
		}
		memberService.applyRevokePartner(revokeMsg, authUser.getId());
		return ResultUtil.success();
	}

	@ApiOperation(value = "申请撤销详情页")
	@RequestMapping("/applyRevokePage")
	public ResultMessage<RevokeApplyVo> applyRevokePage() {
		AuthUser authUser = UserContext.getCurrentUser();
		if (authUser == null) {
			return ResultUtil.error(ResultCode.USER_NOT_LOGIN);
		}
		return ResultUtil.data(memberService.applyRevokePage(authUser.getId()));
	}

	@ApiOperation(value = "申请撤销")
	@RequestMapping("/applyRevoke")
	public ResultMessage<Boolean> applyRevoke(@RequestParam("auditId") String auditId) {
		return ResultUtil.data(memberService.applyRevoke(auditId));
	}

	@ApiOperation(value = "根据用户id获取用户和店铺信息")
	@RequestMapping("/getUserInfoById")
	public ResultMessage<List<MemberVO>> getUserInfoById(String memberIds, String storeIds) {
		List<String> str1 = StringUtils.isNotEmpty(memberIds) ? Arrays.asList(memberIds.split(",")) : null;
		List<String> str2 = StringUtils.isNotEmpty(storeIds) ? Arrays.asList(storeIds.split(",")) : null;
		return ResultUtil.data(memberService.getUserInfoById(str1, str2));
	}

	@ApiOperation(value = "绑定推广码")
	@RequestMapping("/bindTempEx")
	public ResultMessage bindTempEx(String extensionCode) {
		AuthUser authUser = UserContext.getCurrentUser();
		if (authUser == null) {
			return ResultUtil.error(ResultCode.USER_NOT_LOGIN);
		}
		eextensionService.bindTempEx(authUser.getMemberId(), extensionCode);
		return ResultUtil.success();
	}

}
